/**
 * Created by leiweibo on 5/20/15.
 */

var options = {
  'bucket': 'vistrack-attach',
  'save-key': '/{filemd5}{.suffix}',
  'expiration': Math.floor(new Date().getTime() / 1000) + 86400
};
// 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
var policy = window.btoa(JSON.stringify(options));
// 从 UPYUN 用户管理后台获取表单 API
var form_api_secret = 'D7QdgxTWtq3/R9uRDLZIL0kvfB8=';
// 计算签名
var signature = md5(policy + '&' + form_api_secret);

var uploader = new plupload.Uploader({
  runtimes: 'html5,flash,silverlight,html4',
  browse_button: 'pickfiles', // you can pass in id...
  container: document.getElementById('container'), // ... or DOM Element itself
  flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
  silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',

  url: 'http://v0.api.upyun.com/' + options.bucket,

  filters: {
    mime_types: [
      {title: "Image files", extensions: "jpg,gif,png"},
      {title: "Zip files", extensions: "zip"}
    ],
    max_file_size: "1mb",
    prevent_duplicates: true
  },

  multipart_params: {
    'Filename': '${filename}', // adding this to keep consistency across the runtimes
    'Content-Type': '',
    'policy': policy,
    'signature': signature
  },

  init: {
    PostInit: function () {
      //document.getElementById('uploadfiles').onclick = function () {
      //  uploader.start();
      //  return false;
      //};
    },

    FilesAdded: function (up, files) {

      $(".progress-bar").css("width", 0 + '%');
      $(".progress-bar").html(0 + '%');

      for (var i = 0, len = files.length; i < len; i++) {
        var file_name = files[i].name; //文件名
        //构造html来更新UI
        var html = '<div id="file-' + files[i].id + '"></div>';
        $('#preview').html('');
        $(html).appendTo('#preview');
        !function (i) {
          previewImage(files[i], function (imgsrc) {
            $('#file-' + files[i].id).append('<img width=0 src="' + imgsrc + '" />');
            $('#file-' + files[i].id + '>img').animate({width: '200'}, "slow");
          })
        }(i);
      }

      $(".progress").removeClass('hidden');
        uploader.start();

    },

    UploadProgress: function (up, file) {
      $(".progress-bar").css("width", file.percent + '%');
      $(".progress-bar").html(file.percent + '%');
    },

    FileUploaded: function (up, file, info) {
      var response = JSON.parse(info.response);
      console.log(response.url);
      $("#avatar").attr('value', response.url);
    },

    Error: function (up, err) {
      var msg = '';
      if (err.code == -600) {
        msg = '文件指定超过大小';
      }

      bootbox.setDefaults("locale", "zh_CN");
      bootbox.alert(msg);
    }
  }
});

function previewImage(file, callback) {//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
  if (!file || !/image\//.test(file.type)) return; //确保文件是图片
  if (file.type == 'image/gif') {//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
    var fr = new mOxie.FileReader();
    fr.onload = function () {
      callback(fr.result);
      fr.destroy();
      fr = null;
    }
    fr.readAsDataURL(file.getSource());
  } else {
    var preloader = new mOxie.Image();
    preloader.onload = function () {
      preloader.downsize(200, 300);//先压缩一下要预览的图片,宽300，高300
      var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
      callback && callback(imgsrc); //callback传入的参数为预览图片的url
      preloader.destroy();
      preloader = null;
    };
    preloader.load(file.getSource());
  }
}

uploader.init();